//
//  ucfCallMgr.m
//  WXIM
//
//  Created by fusuwei on 14-10-13.
//  Copyright (c) 2014年 naren. All rights reserved.
//

#import "ucfCallMgr.h"
#import "YY_AsyncSocket.h"
#import "PublicMacros.h"
#import "ucfCallMgrDef.h"
#import "UcfgroupXMPPManger.h"
#import "ucfSocket.h"

#import "ucfRecord.h"
#import "ucfPlay.h"
//#import <AVFoundation/AVFoundation.h>


//主叫方与被叫方分别与转发服务器连接建立tcp连接后，发送会话信息，包括如下几个字段：
//
//Sessionid	32字节
//Jid长度	2字节整数，网络字节序传输
//Jid	jid字符串


@interface ucfCallMgr()<AsyncSocketDelegate, ucfSocketDelegate>
{
    NSString *sessionIdString;
    ucfSocket *ucfsocket;
    
    ucfRecord *recorder;
    ucfPlay *player;
    BOOL flag;
}
@end

@implementation ucfCallMgr



static ucfCallMgr *sharedManager;

+(ucfCallMgr*)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager=[[ucfCallMgr alloc] init];

    });
    
    return sharedManager;
}

- (void)dealloc
{
    
}

#pragma mark --didReceivePresence--
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
//    NSLog(@"didReceivePresence : %@", [presence fromStr]);
    NSLog(@"didReceivePresence: presence: %@",presence);
    
  //  NSString *from = [presence fromStr];
    NSString *to = [presence toStr];
    
    //当前用户
 //   NSString *myuserId = [[sender myJID] user];
    
    //取得好友状态 subscribed 通过验证好友添加请求 unsubscribed 对方拒绝
 //   NSString *presenceType = [presence type]; //available 上线/unavailable 下线
    //在线用户
 //   NSString *presenceFromUser = [[presence from] user];
        

    if ([presence.type isEqualToString:@"oncall"])
    {
        //NSXMLElement *query = iq.childElement;
        NSXMLElement *query = [presence elementForName:@"query" xmlns:@"http://jabber.org/protocol/reply"];
        
        NSArray *sessionA = [query elementsForName:@"session"];
        
        for (NSXMLElement *session in sessionA)
        {
            sessionIdString = [session stringValue];
        }
        WXLog(@"sessionIdString1= %@",sessionIdString);
        
        const char *sessionid_char = [sessionIdString cStringUsingEncoding:NSASCIIStringEncoding];
        const char *to_char = [to cStringUsingEncoding:NSASCIIStringEncoding];
        unsigned char* senddata = malloc(512);
        unsigned short jidlen = [to length];
        
        unsigned short dstlen = htons(jidlen);
        
        memcpy(senddata, sessionid_char, strlen(sessionid_char));
        memcpy(senddata+strlen(sessionid_char), &dstlen, 2);
        memcpy(senddata+strlen(sessionid_char)+2, to_char, jidlen);
        
        unsigned short debuglen = strlen(sessionid_char)+2 + jidlen;
        NSData *dataa = [NSData dataWithBytes:senddata length:debuglen];
        
        NSLog(@"999999999999999");
        ucfsocket = [[ucfSocket alloc] init];
        [ucfsocket writeDataOnOtherThread:dataa];
    }
    else if ([presence.type isEqualToString:@"member"])
    {
        NSXMLElement *query = [presence elementForName:@"x" xmlns:@"http://jabber.org/protocol/reply"];
        
        NSArray *sessionA = [query elementsForName:@"session"];
        NSXMLElement *item = [query elementForName:@"item"];
        NSString *ddbug = [item name];
        WXLog(@"ddbug= %@",ddbug);
        
        NSXMLElement *session = [query elementForName:@"session"];
        NSString *ddbug2 = [session name];
        WXLog(@"ddbug2= %@",ddbug2);
        
        for (NSXMLElement *session in sessionA)
        {
            if ([[session name] isEqualToString:@"session"]) {
                sessionIdString = [session stringValue];
                if ((self.delegate != nil) &&[self.delegate respondsToSelector:@selector(requestCreateSessionState:)]) {
                    [self.delegate requestCreateSessionState:YES];
                }
            }
            if ([[session name] isEqualToString:@"item"]) {
                NSString *onlineContactId = [session stringValue];
                if ((self.delegate != nil) &&[self.delegate respondsToSelector:@selector(joinSessionContactId:state:)]) {
                    [self.delegate joinSessionContactId:onlineContactId state:@"online"];
                }
            }
        }
        WXLog(@"sessionIdString2= %@",sessionIdString);

    }
    else if ([presence.type isEqualToString:@"online"])
    {
        NSXMLElement *query = [presence elementForName:@"query" xmlns:@"http://jabber.org/protocol/reply"];
        
        NSArray *sessionA = [query elementsForName:@"session"];
        
        for (NSXMLElement *session in sessionA)
        {
            if ([[session name] isEqualToString:@"session"]) {
                sessionIdString = [session stringValue];
            }
            if ([[session name] isEqualToString:@"item"]) {
                sessionIdString = [session stringValue];
            }
        }
        WXLog(@"sessionIdString3= %@",sessionIdString);
        
        if ((self.delegate != nil) &&[self.delegate respondsToSelector:@selector(joinSessionContactId:state:)]) {
            [self.delegate joinSessionContactId:sessionIdString state:@"online"];
        }
    }
    else if ([presence.type isEqualToString:@"offline"])
    {
        NSXMLElement *query = [presence elementForName:@"query" xmlns:@"http://jabber.org/protocol/reply"];
        
        NSArray *sessionA = [query elementsForName:@"session"];
        
        for (NSXMLElement *session in sessionA)
        {
            sessionIdString = [session stringValue];
        }
        WXLog(@"sessionIdString4= %@",sessionIdString);
        if ((self.delegate != nil) &&[self.delegate respondsToSelector:@selector(joinSessionContactId:state:)]) {
            [self.delegate joinSessionContactId:sessionIdString state:@"online"];
        }
    }
}

#pragma mark -  --------------*********didReceiveIQ**********--------------------
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    WXLog(@"didReceiveIQ: 收到iq id：%@\n\r",[iq elementID]);
    
    NSLog(@"收到iq:%@\n\r",iq);
    
    NSString *from = [[iq from] bare]; //iq.fromStr;
 //   NSString *to = [[iq to] bare]; //iq.toStr;
    
    if ([@"error" isEqualToString:iq.type])
    {
        return YES;
    }
    
    if ([@"result" isEqualToString:iq.type])
    {
        //上传手机联系人后返回数据，已经在易言注册但不是本人好友的列表 回调
        if ([iq.elementID isEqualToString:ucfCallMgr_requestCreateSessiontoContact])
        {
            NSLog(@"ucfCallMgr_requestCreateSessiontoContact");
            
            //NSXMLElement *query = iq.childElement;
            NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/reply"];
            
            NSArray *sessionA = [query elementsForName:@"session"];
            
            for (NSXMLElement *session in sessionA)
            {
                sessionIdString = [session stringValue];
                if ((self.delegate != nil) &&[self.delegate respondsToSelector:@selector(requestCreateSessionState:)]) {
                    [self.delegate requestCreateSessionState:YES];
                }
            }
            
            const char *sessionid_char = [sessionIdString cStringUsingEncoding:NSASCIIStringEncoding];
            const char *from_char = [from cStringUsingEncoding:NSASCIIStringEncoding];
            unsigned char* senddata = malloc(512);
            unsigned short jidlen = [from length];

            unsigned short dstlen = htons(jidlen);
            
            memcpy(senddata, sessionid_char, strlen(sessionid_char));
            memcpy(senddata+strlen(sessionid_char), &dstlen, 2);
            memcpy(senddata+strlen(sessionid_char)+2, from_char, jidlen);
            
            NSUInteger debuglen = strlen(sessionid_char)+2 + jidlen;
       
            NSLog(@"888888888888888888888888");
            NSData *dataa = [NSData dataWithBytes:senddata length:debuglen];
            ucfsocket = [[ucfSocket alloc] init];
            ucfsocket.delegate = self;
            [ucfsocket writeDataOnOtherThread:dataa];
            return YES;
        }
        
    }
    
    return YES;
}

//1、主叫方xmpp向服务器申请建立会话，消息格式如下：
//<iq from=zh@wx.com type=get>
//  <query xmlns=http://jabber.org/protocol/reply>
//      <item>zhh1@wx.com</item>
//      <item>zhh2@wx.com</item>
//  </query>
//</iq>
- (BOOL)requestCreateSession:(NSString *)fromId toContact:(NSArray *)toContactIdList
{
    NSInteger toClistCount = [toContactIdList count];
    if (fromId == nil || toContactIdList ==nil || toClistCount < 1) {
        return NO;
    }
    
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    [iq addAttributeWithName:@"id" stringValue:@"ucfCallMgr_requestCreateSessiontoContact"];
    [iq addAttributeWithName:@"from" stringValue:fromId];
    [iq addAttributeWithName:@"type" stringValue:@"get"];
    
    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/reply"];
    
    for (int i=0; i<toClistCount; i++)
    {
        NSXMLElement *item = [NSXMLElement elementWithName:@"item" stringValue:[toContactIdList objectAtIndex:i]];
        [query addChild:item];
    }
    
    [iq addChild:query];
    [[UcfgroupXMPPManger sharedInstance].xmppStream sendElement:iq];
    return YES;
}

//发送录音数据
- (BOOL) sendSocketData:(NSData *)data
{
    if (ucfsocket) {
        [ucfsocket writeDataOnOtherThread:data];
        return YES;
    }
    return NO;
}



#pragma mark -
#pragma mark Delegate

- (void)onSocket:(YY_AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"willDisconnectWithError:%@",err);

}

- (void)onSocketDidDisconnect:(YY_AsyncSocket *)sock
{
    NSLog(@"onSocketDidDisconnect");
}

- (void)onCocketConnectToHost:(NSString*)state
{
    NSLog(@"onCocketConnectToHost");
    
    [self.delegate requestCreateSessionState:YES];
    
    recorder = [[ucfRecord alloc] init];
    player = [[ucfPlay alloc] init];
    
    UInt32 category = kAudioSessionCategory_PlayAndRecord;
    OSStatus error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
    if (error) printf("couldn't set audio category!");
    
    UInt32 inputAvailable = 0;
    UInt32 size = sizeof(inputAvailable);
    
    // we do not want to allow recording if input is not available
    error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable);
    if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", (int)error);
    
    
    error = AudioSessionSetActive(true);
    if (error) printf("AudioSessionSetActive (true) failed");
    
    [player initPlay];
    
    [self btnRecord:nil]; //开始录音
}

- (void)onSocket:(YY_AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    //NSString *rcvdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
   // if(rcvdata)
    {
        //处理受到的数据
//        NSLog(@"收到的数据:%@",rcvdata);
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"收到数据" message:rcvdata delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//        [alert show];
        //unsigned char *buffer = (unsigned char *)[data bytes];
        NSInteger buflen = [data length];
        NSLog(@"收到的数据长度:%ld",(long)buflen);
        
    }
//    else
//    {
//        NSLog(@"Error converting received data into UTF-8 String");
//    }
    
    //    NSString *message= @"连接成功";
    //    NSData *cmdData = [message dataUsingEncoding:NSUTF8StringEncoding];
    //    [sock writeData:cmdData withTimeout:-1 tag:0];
    
    
    
    [sock readDataWithTimeout:-1 tag:0];
}

-(void)onSocket:(YY_AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataWithTag:%ld",tag);
    [sock readDataWithTimeout:-1 tag:0];

}

#pragma -------------录音和播放------------
- (void)btnRecord:(id)sender {
    NSLog(@"btnRecord");
    if (flag == YES) {
        [recorder pause];
        flag = NO;
    } else{
        [recorder start];
        flag = YES;
    }
}

- (void)btnComplete:(id)sender {
    [recorder stop];
}

//- (void)btnPlay:(id)sender {
//    player = [[Play alloc]init];
//    [player Play:[recorder getBytes] Length:recorder.audioDataLength];
//}

- (void)btnPlay:(NSData*)data
{
    NSLog(@"ffffffff----btnPlay");
    
    [player readPCMdataAndPlayData:data];
}

@end
